package com.yami.shop.cp.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.cp.comment.dto.*;
import com.yami.shop.cp.comment.enums.CollaborativePurchaseBasketEnum;
import com.yami.shop.cp.comment.enums.CollaborativePurchaseStatusEnum;
import com.yami.shop.cp.comment.model.CollaborativePurchase;
import com.yami.shop.cp.comment.model.CollaborativePurchaseAddr;
import com.yami.shop.cp.comment.service.CollaborativePurchaseAddrService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseBasketService;
import com.yami.shop.cp.comment.service.CollaborativePurchaseService;
import com.yami.shop.security.api.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;


@RestController
@RequestMapping("/p/cp")
@Api(tags = "协同采购接口")
@AllArgsConstructor
public class CollaborativePurchaseController {

    private final CollaborativePurchaseService collaborativePurchaseService;
    private CollaborativePurchaseBasketService collaborativePurchaseBasketService;
    private CollaborativePurchaseAddrService collaborativePurchaseAddrService;

    @PostMapping("/add")
    @ApiOperation(value = "添加协同采购单")
    public ResponseEntity<String> addCollaborativePurchase(@Valid @RequestBody CollaborativePurchaseMergerDto collaborativePurchaseMergerDto) {
        String userId = SecurityUtils.getUser().getUserId();
        collaborativePurchaseMergerDto.setUserId(userId);
        if (collaborativePurchaseMergerDto.getEndTime().isBefore(collaborativePurchaseMergerDto.getStartTime())){
            return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.time.error"));
        }
        collaborativePurchaseService.createCollaborativePurchase(collaborativePurchaseMergerDto);
        return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.added.successfully"));
    }

    @GetMapping("/info/{id}")
    @ApiOperation(value = "根据协同采购单id查询采购单详情")
    public ResponseEntity<CollaborativePurchaseMergerDto> collaborativePurchaseById(@PathVariable("id") String collaborativePurchaseId) {
        String userId = SecurityUtils.getUser().getUserId();
        CollaborativePurchaseMergerDto collaborativePurchaseMergerDto = collaborativePurchaseService.queryCollaborativePurchaseMergerDto(userId, collaborativePurchaseId);

        return ResponseEntity.ok(collaborativePurchaseMergerDto);
    }

    @GetMapping("/listCP/{status}")
    @ApiOperation(value = "根据采购单列表状态查询当前用户的采购单列表")
    public ResponseEntity<IPage<CollaborativePurchaseInfoDto>> listCollaborativePurchaseByUserIdAndStatus(PageParam page, @PathVariable("status") String status) {
        String userId = SecurityUtils.getUser().getUserId();
        // 设置按照创建时间排序
        page.addOrder(OrderItem.desc("create_time"));
        // 获取当前用户的协同采购单
        IPage<CollaborativePurchase> collaborativePurchaseIPage = collaborativePurchaseService.pageByUserIdAndStatus(page, userId, status);
        // 根据协同采购单查询出采购单产品信息
        List<CollaborativePurchaseInfoDto> collaborativePurchaseInfoDtoList = new ArrayList<>();
        for (CollaborativePurchase collaborativePurchase : collaborativePurchaseIPage.getRecords()) {
            List<String> images = new ArrayList<>();
            // 暂时先获取全部提报信息，然后遍历获取三个图片地址，后面有时间再优化
            List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseSubmitShopCartItems = collaborativePurchaseBasketService.getShopCartItemsByCollaborativePurchaseId(collaborativePurchase.getId());
            for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseSubmitShopCartItems) {
                images.add(collaborativePurchaseShopCartItemDto.getPic());
                if (images.size() == 3) {
                    break;
                }
            }
            CollaborativePurchaseInfoDto collaborativePurchaseInfoDto = new CollaborativePurchaseInfoDto();
            collaborativePurchaseInfoDto.setCollaborativePurchase(collaborativePurchase);
            collaborativePurchaseInfoDto.setImages(images);
            collaborativePurchaseInfoDto.setProdCount(collaborativePurchaseSubmitShopCartItems.size());
            collaborativePurchaseInfoDtoList.add(collaborativePurchaseInfoDto);
        }

        IPage<CollaborativePurchaseInfoDto> purchaseInfoDtoIPage = new PageParam<>();
        purchaseInfoDtoIPage.setSize(collaborativePurchaseIPage.getSize());
        purchaseInfoDtoIPage.setTotal(collaborativePurchaseIPage.getTotal());
        purchaseInfoDtoIPage.setCurrent(collaborativePurchaseIPage.getCurrent());
        purchaseInfoDtoIPage.setPages(collaborativePurchaseIPage.getPages());
        purchaseInfoDtoIPage.setRecords(collaborativePurchaseInfoDtoList);

        return ResponseEntity.ok(purchaseInfoDtoIPage);
    }


    @PutMapping("/update")
    @ApiOperation(value = "修改协同采购单")
    public ResponseEntity<String> updateCollaborativePurchase(@Valid @RequestBody CollaborativePurchaseMergerDto collaborativePurchaseMergerDto) {
        String userId = SecurityUtils.getUser().getUserId();
        collaborativePurchaseMergerDto.setUserId(userId);
        if (collaborativePurchaseMergerDto.getEndTime().isBefore(collaborativePurchaseMergerDto.getStartTime())){
            return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.time.error"));
        }
        collaborativePurchaseService.updateCollaborativePurchase(collaborativePurchaseMergerDto);
        return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.update.successfully"));
    }

    @GetMapping("/sp/listCP/{status}")
    @ApiOperation(value = "获取当前提报人的协同采购单")
    public ResponseEntity<IPage<CollaborativePurchaseInfoDto>> listCollaborativePurchaseBySubmitPersonIdAndStatus(PageParam page, @PathVariable("status") String status) {
        String mobile = SecurityUtils.getSubmitPerson().getMobile();
        page.addOrder(OrderItem.desc("cp.create_time"));
        IPage<CollaborativePurchase> collaborativePurchaseIPage = collaborativePurchaseService.pageBySubmitPersonIdAndStatus(page, mobile, status);
        // 根据协同采购单查询出采购单产品信息
        List<CollaborativePurchaseInfoDto> collaborativePurchaseInfoDtoList = new ArrayList<>();
        for (CollaborativePurchase collaborativePurchase : collaborativePurchaseIPage.getRecords()) {
            List<String> images = new ArrayList<>();
            int prodCount = 0;
            // 暂时先获取全部提报信息，然后遍历获取三个图片地址，后面有时间再优化
            List<CollaborativePurchaseShopCartItemDto> collaborativePurchaseSubmitShopCartItems = collaborativePurchaseBasketService.getShopCartItemsByCollaborativePurchaseId(collaborativePurchase.getId());
            for (CollaborativePurchaseShopCartItemDto collaborativePurchaseShopCartItemDto : collaborativePurchaseSubmitShopCartItems) {
                if (images.size() < 3) {
                    images.add(collaborativePurchaseShopCartItemDto.getPic());
                }
                prodCount = prodCount + collaborativePurchaseShopCartItemDto.getProdCount();
            }
            CollaborativePurchaseInfoDto collaborativePurchaseInfoDto = new CollaborativePurchaseInfoDto();
            collaborativePurchaseInfoDto.setCollaborativePurchase(collaborativePurchase);
            collaborativePurchaseInfoDto.setImages(images);
            collaborativePurchaseInfoDto.setProdCount(prodCount);
            collaborativePurchaseInfoDtoList.add(collaborativePurchaseInfoDto);
        }
        IPage<CollaborativePurchaseInfoDto> purchaseInfoDtoIPage = new PageParam<>();
        purchaseInfoDtoIPage.setSize(collaborativePurchaseIPage.getSize());
        purchaseInfoDtoIPage.setTotal(collaborativePurchaseIPage.getTotal());
        purchaseInfoDtoIPage.setCurrent(collaborativePurchaseIPage.getCurrent());
        purchaseInfoDtoIPage.setPages(collaborativePurchaseIPage.getPages());
        purchaseInfoDtoIPage.setRecords(collaborativePurchaseInfoDtoList);

        return ResponseEntity.ok(purchaseInfoDtoIPage);
    }

    @GetMapping("/sp/info/{id}")
    @ApiOperation(value = "根据协同采购单id查询采购单详情")
    public ResponseEntity<Map<String, Object>> spCollaborativePurchaseById(@PathVariable("id") String collaborativePurchaseId) {
        Map<String, Object> map = new HashMap<>(4);
        CollaborativePurchase collaborativePurchase = collaborativePurchaseService.getOne(new LambdaQueryWrapper<CollaborativePurchase>()
                .eq(CollaborativePurchase::getId, collaborativePurchaseId));
        map.put("collaborativePurchase", collaborativePurchase);
        CollaborativePurchaseAddr cpAddr = collaborativePurchaseAddrService.getOne(new LambdaQueryWrapper<CollaborativePurchaseAddr>()
                .eq(CollaborativePurchaseAddr::getCollaborativePurchaseId, collaborativePurchaseId));
        map.put("cpAddr", cpAddr);
        return ResponseEntity.ok(map);
    }

    @GetMapping("/sp/prod/infoAndCount/{id}")
    @ApiOperation(value = "提报人查询协同采购单中商品的信息")
    public ResponseEntity<SPCPProdInfoAndCount> getSPProdInfoAndCountById(@PathVariable("id") String collaborativePurchaseId) {
        List<CollaborativePurchaseShopCartItemDto> cpShopCartItemDtos = collaborativePurchaseBasketService.getShopCartItemsByCollaborativePurchaseId(collaborativePurchaseId);
        SPCPProdInfoAndCount spcpProdInfoAndCount = new SPCPProdInfoAndCount();
        spcpProdInfoAndCount.setCpShopCartItemDtoList(cpShopCartItemDtos);
        for (CollaborativePurchaseShopCartItemDto cpShopCartItemDto : cpShopCartItemDtos) {
            spcpProdInfoAndCount.setProdCount(spcpProdInfoAndCount.getProdCount() + cpShopCartItemDto.getProdCount());
            spcpProdInfoAndCount.setProdTotalAmount(Arith.add(spcpProdInfoAndCount.getProdTotalAmount(), cpShopCartItemDto.getProductTotalAmount()));
        }
        return ResponseEntity.ok(spcpProdInfoAndCount);
    }


    @GetMapping({"/sp/cpOrderNum/{id}","/user/cpOrderNum/{id}"})
    @ApiOperation(value = "提报人获取当前协同采购已下单的订单号和创建时间、商品总数")
    public ResponseEntity<List<CPOrderDto>> getCPOrderNumById(@PathVariable("id") String cpId) {
        return ResponseEntity.ok(collaborativePurchaseService.getCPOrderNumById(cpId));
    }




    @GetMapping("/basket/prod/info/{id}")
    @ApiOperation(value = "用户查询协同采购单清单产品详情")
    public ResponseEntity<CollaborativePurchaseBasketProdInfoDto> basketProdInfoById(PageParam page, @PathVariable("id") String collaborativePurchaseId) {
        CollaborativePurchase collaborativePurchase = collaborativePurchaseService.getById(collaborativePurchaseId);
        // 分页获取协同采购单已提报产品
        IPage<CollaborativePurchaseShopCartItemDto> collaborativePurchaseSubmitShopCartItems = collaborativePurchaseBasketService.pageShopCartItemsByCollaborativePurchaseId(page, collaborativePurchaseId, CollaborativePurchaseBasketEnum.SUBMIT.getValue());
        CollaborativePurchaseBasketProdInfoDto collaborativePurchaseBasketProdInfoDto = new CollaborativePurchaseBasketProdInfoDto();
        collaborativePurchaseBasketProdInfoDto.setCollaborativePurchase(collaborativePurchase);
        collaborativePurchaseBasketProdInfoDto.setCollaborativePurchaseShopCartItemDtoList(collaborativePurchaseSubmitShopCartItems);
        return ResponseEntity.ok(collaborativePurchaseBasketProdInfoDto);
    }

    @GetMapping("/{collaborativePurchaseId}/spInfoAndCount")
    @ApiOperation(value = "根据协同采购id查询提报人详情和统计")
    public ResponseEntity<CPSubmitPersonCount> getCPSubmitPersonCount(@PathVariable("collaborativePurchaseId") String collaborativePurchaseId) {
        return ResponseEntity.ok(collaborativePurchaseService.getCPSubmitPersonCount(collaborativePurchaseId));
    }

    @GetMapping("/cpProdInfoAndCount")
    @ApiOperation(value = "根据协同采购id查看商品下单情况")
    public ResponseEntity<CPProdInfoAndCountDto> getCPProdInfoAndCount(@RequestParam(value = "cpId", required = true) String cpId) {
        List<CPProdInfo> cpProdInfos = collaborativePurchaseBasketService.getCPSubmitAndCompletePordInfo(cpId);
        CPProdInfoAndCountDto cpProdInfoAndCountDto = new CPProdInfoAndCountDto();
        cpProdInfoAndCountDto.setCpProdInfos(cpProdInfos);
        for (CPProdInfo cpProdInfo : cpProdInfos) {
            if (Objects.equals(CollaborativePurchaseBasketEnum.SUBMIT.getValue(), cpProdInfo.getStatus())) {
                cpProdInfoAndCountDto.setSubmitProdCount(cpProdInfoAndCountDto.getSubmitProdCount() + cpProdInfo.getBasketCount());
                cpProdInfoAndCountDto.setSubmitProdTotalAmount(Arith.add(cpProdInfoAndCountDto.getSubmitProdTotalAmount(), Arith.mul(cpProdInfo.getPrice(), cpProdInfo.getBasketCount())));
            }
            if (Objects.equals(CollaborativePurchaseBasketEnum.COMPLETE.getValue(), cpProdInfo.getStatus())) {
                cpProdInfoAndCountDto.setCompleteProdCount(cpProdInfoAndCountDto.getCompleteProdCount() + cpProdInfo.getBasketCount());
                cpProdInfoAndCountDto.setCompleteProdTotalAmount(Arith.add(cpProdInfoAndCountDto.getCompleteProdTotalAmount(), Arith.mul(cpProdInfo.getPrice(), cpProdInfo.getBasketCount())));
            }
        }
        return ResponseEntity.ok(cpProdInfoAndCountDto);
    }

    @PutMapping("/completeCP/{id}")
    @ApiOperation(value = "完成协同采购单")
    public ResponseEntity<String> completeCP(@PathVariable(value = "id") String cpId) {
        collaborativePurchaseService.update(new LambdaUpdateWrapper<CollaborativePurchase>()
                .set(CollaborativePurchase::getStatus, CollaborativePurchaseStatusEnum.COMPLETE.getValue())
                .eq(CollaborativePurchase::getId, cpId));
        return ResponseEntity.ok(I18nMessage.getMessage("yami.collaborative.purchase.complete.successfully"));
    }


}
